package com.haohan.cloud.framework.dto.api;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.haohan.cloud.framework.entity.BaseList;
import com.haohan.cloud.framework.entity.BaseResp;
import com.haohan.cloud.framework.utils.CoreLogUtils;
import com.haohan.cloud.framework.utils.JacksonUtils;

import java.io.Serializable;
import java.util.List;

/**
 * 返回数据基类
 * @author zhaokuner
 *
 */
public class ApiResp extends BaseResp {

	/**
	 *
	 */
	private static final long serialVersionUID = 3515924068002172779L;

	/** 是否加密 */
	protected Boolean encrypt = false;
	/** 回溯信息 */
	protected String state;
	/** 时间戳（毫秒 */
	protected Long timestamp = System.currentTimeMillis();
	/** 业务数据 */
	protected String data;
	/** 业务数据 */
	@JsonIgnore
	protected ApiRespData apiRespData = new ApiRespData();

	@JsonIgnore
	private String sercertKey;

	public String toJson() {
		if ((null == data || data.isEmpty()) && null != apiRespData) {
			this.setData(apiRespData.toJson());
		}
		String json = JacksonUtils.toJson(this);
		CoreLogUtils.serviceApiLog("API返回："+json);
		return json;
	}

	public Boolean getEncrypt() {
		return encrypt;
	}

	public void setEncrypt(Boolean encrypt) {
		this.encrypt = encrypt;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public Long getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(Long timestamp) {
		this.timestamp = timestamp;
	}

	public String getData() {
		return this.data;
	}

	public void setData(String data) {
		this.data = data;
	}

	@SuppressWarnings("unchecked")
	public <T extends Serializable> T dataExt() {
		return (T) this.apiRespData.getExt();
	}

	public void setExt(Serializable ext) {
		this.apiRespData.setExt(ext);
	}

	@SuppressWarnings("unchecked")
	public <T extends ApiRespData> T getApiRespData() {
		return (T) apiRespData;
	}

	public void setApiRespData(ApiRespData apiRespData) {
		this.apiRespData = apiRespData;
	}

	public String getSercertKey() {
		return sercertKey;
	}

	public void setSercertKey(String sercertKey) {
		this.sercertKey = sercertKey;
	}

	/**
	 * 不带分页，仅是list数据的转换
	 */
	@SuppressWarnings("unchecked")
	public <T extends Serializable> void setList(List<T> list) {

		ApiRespListData<T> result = null;

		if (this.apiRespData instanceof ApiRespListData) {
			result = (ApiRespListData<T>) this.apiRespData;
		} else {
			result = new ApiRespListData<T>();
			this.apiRespData = result;
		}
		result.setList(list);
	}
	/**
	 * 带分页信息
	 * @param list
	 */
	@SuppressWarnings("unchecked")
	public <T extends Serializable> void setBaseList(BaseList<T> list) {

		ApiRespListData<T> result = null;

		if (this.apiRespData instanceof ApiRespListData) {
			result = (ApiRespListData<T>) this.apiRespData;
		} else {
			result = new ApiRespListData<T>();
			this.apiRespData = result;
		}
		if (list != null) {
			result.setTotalRows(list.getTotalRows());
			result.setList(list.getList());
		}
	}
}
